//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// 			VisualNovelToolkit		     /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe.	/_/_/_/_/_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.

using UnityEngine;
using System.Collections;

namespace ViNoToolkit{

	/// <summary>
	/// Tokenizer.
	/// </summary>
	public class Tokenizer {
		public enum ReadMode{
			GLOBAL=0,
			TAG,
			READ_ATTRIBUTE,
	//		TEXT,
		}
		static private ReadMode m_ReadMode = ReadMode.GLOBAL;
		static public ReadMode readMode{
			get{ return m_ReadMode; }
		}

		static public string singleTokenStr{
			get{ 
				string ret = "";
				switch( readMode ){
					case ReadMode.GLOBAL:
						ret =  "\n*<>@#[]$={}:\"";
						break;

					case ReadMode.TAG:			
						// do not include *. for [jump] tag or [link] tag.	
						// for example , [jump target=*start].
						ret = "\n<>@[]={}:";//\"";
						break;

					case ReadMode.READ_ATTRIBUTE:
						ret = " \n<>@[]{}:";//\"";
						break;


	/*				case ReadMode.TEXT:
						ret = "\"";					
						break;
	//*/					
				}
				return ret;
			}
		}

		static public string whiteSpaceStr{
			get{ return " \t\r"; }
		}

		public string currentToken{
			get{ return m_CurrentToken; } 
		}	

		public string text{
			get{ return m_Text; } 
		}

		public int position{
			get{ return m_Pos; }
		}

		private int m_Pos = 0;	
		private string m_CurrentToken;
	//	private string m_PrevToken;
		private string m_Text;	

		public Tokenizer(){}

		public Tokenizer( string text , int pos ){
			m_Text = text;
			m_Pos = pos;
		}

		public void Init(){
			m_Text = "";
			m_CurrentToken = "";
	//		m_PrevToken = "";
			m_Pos = 0;
		}

		public void ChangeReadMode( ReadMode mode ){
			m_ReadMode = mode;
		}

		public void ChangeReadModeGLOBAL(){
			m_ReadMode = ReadMode.GLOBAL;
		}

		public void ChangeReadModeTAG(){
			m_ReadMode = ReadMode.TAG;
		}

		public string GetToken(){
			// Reached end and return.
			if( IsOutOfRangePos() ){
				return string.Empty;
			}

	//		m_PrevToken = m_CurrentToken;	

			// Skip White Space.
			while( whiteSpaceStr.IndexOf( m_Text[ m_Pos ] ) != -1 ){
				m_Pos++;
				if( IsOutOfRangePos() ){
					break;
				}
			}	

			// Check current pos is single character token.
			if( singleTokenStr.IndexOf( m_Text[ m_Pos ] ) != -1 ){
				m_CurrentToken = m_Text[ m_Pos ].ToString();
				m_Pos++;
				return m_CurrentToken;
			}

			// .
			System.Text.StringBuilder tokenStr = new System.Text.StringBuilder();
			while( !( ( whiteSpaceStr.IndexOf( m_Text[ m_Pos ] ) != -1 ) || ( singleTokenStr.IndexOf( m_Text[ m_Pos ] ) != -1 ) ) ){
				tokenStr.Append( m_Text[ m_Pos ] );
				m_Pos++;
				if( IsOutOfRangePos() ){
					break;
				}
			}
			return tokenStr.ToString();		
		}	

		public bool IsOutOfRangePos (){
			return ( m_Text.Length <= m_Pos );
		}	

	}
}
